package com.atguigu.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduService.entity.EduSubject;
import com.atguigu.eduService.entity.excel.SubjectData;
import com.atguigu.eduService.entity.subject.OneSubject;
import com.atguigu.eduService.entity.subject.TwoSubject;
import com.atguigu.eduService.listener.subjectExcelListener;
import com.atguigu.eduService.mapper.EduSubjectMapper;
import com.atguigu.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-05-12
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new subjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //先查一级分类
        QueryWrapper<EduSubject> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id","0");
        List<EduSubject> oneSubjectLists = baseMapper.selectList(wrapper1);
        //再查二级分类
        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper1.ne("parent_id","0");
        List<EduSubject> twoSubjectLists = baseMapper.selectList(wrapper2);
        List<OneSubject> finalSubject = new ArrayList<>();
        //封装一级分类
        for (EduSubject temp1 : oneSubjectLists) {
            OneSubject oneSubject = new OneSubject();
            //传统方式
//            oneSubject.setId(temp1.getId());
//            oneSubject.setTitle(temp1.getTitle());
            //使用工具类
            BeanUtils.copyProperties(temp1, oneSubject);
            List<TwoSubject> twoSubjectList = new ArrayList<>();
            for (EduSubject temp2 : twoSubjectLists) {
                if (oneSubject.getId().equals(temp2.getParentId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(temp2, twoSubject);
                    twoSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjectList);
            finalSubject.add(oneSubject);
        }
        //封装二级分类
        return finalSubject;
    }
}
